#include "addpointdlg.h"
#include <set>

void addPointDlg::addItem(int i, const Point &p)
{
    auto label=new QLabel(QString::number(i));
    auto lineEdit1=new QLineEdit(QString::number(p.getX()));
    auto lineEdit2=new QLineEdit(QString::number(p.getY()));
    lineEdit1->setValidator(new QDoubleValidator());
    lineEdit2->setValidator(new QDoubleValidator());
    ui->table_Points->setCellWidget(i,0,label);
    ui->table_Points->setCellWidget(i,1,lineEdit1);
    ui->table_Points->setCellWidget(i,2,lineEdit2);
}

addPointDlg::addPointDlg(QVector<Point> *pointArr)
{
    this->pointArr=pointArr;
    ui=new Ui::pointDialog;
    ui->setupUi(this);

    ui->table_Points->setRowCount(pointArr->size());
    for(int i=0;i<pointArr->size();i++){
        Point p=pointArr->at(i);
        addItem(i,p);
    }

    connect(ui->btn_Add,SIGNAL(clicked()),this,SLOT(addRow()));
    connect(ui->btn_Del,SIGNAL(clicked()),this,SLOT(deleteNowRow()));
}

addPointDlg::~addPointDlg()
{
    delete ui;
}

void addPointDlg::accept()
{
    auto count=ui->table_Points->rowCount();
    pointArr->clear();
    for(int i=0;i<count;i++){
        auto x=dynamic_cast<QLineEdit *>(ui->table_Points->cellWidget(i,1));
        auto y=dynamic_cast<QLineEdit *>(ui->table_Points->cellWidget(i,2));
        pointArr->push_back(Point(x->text().toDouble(),y->text().toDouble()));
    }
    emit pointChanged();
    return QDialog::accept();
}

void addPointDlg::reject()
{
    emit pointUnchanged();
    QDialog::reject();
}

void addPointDlg::addRow()
{
    auto count=ui->table_Points->rowCount();
    ui->table_Points->setRowCount(count+1);
    addItem(count,Point(0,0));
    ui->table_Points->selectRow(count);
}

void addPointDlg::deleteNowRow()
{
    auto row=ui->table_Points->currentRow();
    ui->table_Points->removeRow(row);
}
